<?php

namespace App\Service\playlet;
use App\Model\Applet;
use App\Model\AppletPlayletRel;
use App\Model\DataBackhaulSetting;
use App\Model\DataSpread;
use App\Model\DataSpreadPlatform;
use App\Model\Playlet;
use App\Model\Company;
use App\Model\AppletCompany;
use App\Model\PlayletEpisodes;
use App\Model\RechargeTemplate;
use App\Service\CommicService;
use Hyperf\Utils\ApplicationContext;
use App\Common\Response\SystemCode;
use Hyperf\DbConnection\Db;

class DataSpreadService extends CommicService
{
    const cacheDuration = 60 * 15;
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redisService = $container->get(\Hyperf\Redis\Redis::class);
    }


    const STATUS_ENABLE  = 1;


    public function search(Array $params){

        $keyword     = $params['keyword'] ?? '';
        $company_id  = $params['company_id'] ?? 0;
        $applet_id   = $params['applet_id'] ?? 0;
        $pageSize    = $params['pageSize'] ?? 10;
        $page        = $params['page'] ?? 1;

        $query = DataSpread::query()->select(['id','name','applet_id','playlet_id','company_id','recharge_template_id','playlet_name','playlet_number_name','playlet_number','created_at','updated_at']);

        if ($keyword) {
            $query->orWhere([['name', 'like', '%'.$keyword.'%']]);
        }
        if(!empty($company_id)){
            $query->where(['company_id' => $company_id]);
        }
        if(!empty($applet_id)){
            $query->where(['applet_id' => $applet_id]);
        }

        $models = $query->orderBy('updated_at','desc')->paginate($pageSize,['*'],'page',$page);
        $items = $models->items();
        $selectData = [];
        foreach ($items as $item){
            $data = $item->toArray();
            if(!empty($item->applet)){
                $data['applet_name']  = $item->applet->name;
            }else{
                $data['applet_name']  = '';
            }
            if(!empty($item->template)){
                $data['recharge_template_name']  = $item->template->name;
            }else{
                $data['recharge_template_name']  = '';
            }
            if(!empty($item->company)){
                $data['company_name']  = $item->company->name;
            }else{
                $data['company_name']  = '';
            }

            $selectData[] =$data;

        }
        $data = $models->toArray();
        $data['data'] = $selectData;
        return $data;
    }

    public function createOrUpdate(Array $postData,DataSpread $dataSpreadInfo = null){
        $name = $postData['name'];
        $applet_id = $postData['applet_id'];
        $company_id = $postData['company_id'];
        $user_type =  $postData['user_type'] ?? 1;
        $playlet_id = $postData['playlet_id'];
        $recharge_template_id = $postData['recharge_template_id'] ?? 1;
        $assistant_recharge_template_id = $postData['assistant_recharge_template_id'] ?? 0;
        $spread_platform_id = $postData['spread_platform_id'];
        $playlet_number = $postData['playlet_number'];
        $playlet_number_num = $postData['playlet_number_num'];
        $playlet_number_num_pay = $postData['playlet_number_num_pay'];
        $recharge_template_type = $postData['recharge_template_type'];
        Db::beginTransaction();
        try {
//            var_dump($dataSpreadInfo);
            $model = !empty($dataSpreadInfo)? $dataSpreadInfo : new DataSpread();

            //查看公司是否存在
            $companyData = Company::query()->where(['id' => $company_id])->exists();
            if(empty($companyData)){
                throw new \Exception('公司不存在');
            }
            //查找小程序是否存在
            $appletData = Applet::query()->where(['id' => $applet_id])->exists();
            if(empty($appletData)){
                throw new \Exception('小程序不存在');
            }
            //查看小程序和公司是否存在绑定关系
            $appletCompanyData = AppletCompany::query()->where(['company_id' => $company_id,'applet_id' => $applet_id])->exists();
            if(empty($appletCompanyData)){
                throw new \Exception('公司和小程序不存在绑定关系小程序');
            }
            //查找短剧是否存在
            $playletData = Playlet::query()->where(['id' => $playlet_id])->select(['id','name'])->first();
            if(empty($playletData)){
                throw new \Exception('短剧不存在');
            }
            //查找短剧是否属于这小程序
            $appletPlayletData = AppletPlayletRel::query()->where(['playlet_id' => $playlet_id,'applet_id'=>$applet_id ])->exists();
            if(empty($appletPlayletData)){
                throw new \Exception('短剧不属于这小程序');
            }
            //查询短剧是否拥有这集数
            $playletEpisodesData = PlayletEpisodes::query()->where(['playlet_id' => $playlet_id,'playlet_number'=>$playlet_number ])->select(['playlet_number_name'])->first();
            if(empty($playletEpisodesData)){
                throw new \Exception('短剧不存在这集数');
            }
            //查询短剧是否拥有这集数
            $episodesData = PlayletEpisodes::query()->where(['playlet_id' => $playlet_id,'playlet_number'=>$playlet_number_num])->exists();
            if(empty($episodesData)){
                throw new \Exception('短剧不存在这付费集数');
            }

            if($playlet_number > $playlet_number_num){
                throw new \Exception('投放集数必须小于付费集数!');
            }

            if($recharge_template_type == 1){
                $recharge_template_id = 1;
            }else{
                //查询充值模板是否存在
                $rechargeTemplateData = RechargeTemplate::query()->where(['id' => $recharge_template_id,'company_id' => $company_id,'applet_id' =>$applet_id])->exists();
                if(empty($rechargeTemplateData)){
                    throw new \Exception('充值模板不存在,或者模板不属于该小程序');
                }
            }

            if(!empty($assistant_recharge_template_id) && $assistant_recharge_template_id != 1){

                //查询副充值模板是否存在
                $rechargeTemplateData = RechargeTemplate::query()->where(['id' => $assistant_recharge_template_id,'company_id' => $company_id,'applet_id' =>$applet_id])->exists();
                if(empty($rechargeTemplateData)){
                    throw new \Exception('充值模板不存在,或者模板不属于该小程序');
                }
            }
            //查询投放平台是否存在
            $dataSpreadPlatformData = DataSpreadPlatform::query()->where(['id' => $spread_platform_id])->exists();
            if(empty($dataSpreadPlatformData)){
                throw new \Exception('投放平台不存在');
            }
            $model->applet_id = $applet_id;
            $model->company_id = $company_id;
            $model->playlet_id = $playlet_id;
            $model->user_type = $user_type;
            $model->recharge_template_id = $recharge_template_id;
            $model->assistant_recharge_template_id = $assistant_recharge_template_id;
            $model->spread_platform_id = $spread_platform_id;
            $model->playlet_name = $playletData->name;
            $model->playlet_number = $playlet_number;
            $model->playlet_number_name =$playletEpisodesData->playlet_number_name;
            $model->playlet_number_num =$playlet_number_num;
            $model->playlet_number_num_pay =$playlet_number_num_pay;
            $model->recharge_template_type =$recharge_template_type;
            $model->name = $name;
            if($model->save()){
                //填写小程序路由
                $model->wx_link = 'pages/videopage/videopage?spread_id='.$model->id.'&pid='.$model->playlet_id.'&peid='.$model->playlet_number.'&ut='.$user_type;
                $model->save();

                Db::commit();
                return $this->response(SystemCode::SYSTEM_SUCCESS);
            }else{
                Db::rollBack();
                return $this->response(SystemCode::SYSTEM_ERROR,'保存错误');
            }

        }catch (\Exception $e){
            Db::rollBack();
            return $this->response(SystemCode::SYSTEM_ERROR,$e->getMessage());
        }

    }


    public function batchSettings(Array $params){

        $data_spread_ids = $params['data_spread_ids'];
        $recharge_template_id = $params['recharge_template_id'] ?? '';
        $backhaul_setting_id = $params['backhaul_setting_id'] ?? '';

        $dataSpreadInfo = DataSpread::query()->whereIn('id',$data_spread_ids)->get();

        if($dataSpreadInfo->isNotEmpty()){

            foreach ($dataSpreadInfo as $item){
                $is_update = false;
                if(!empty($recharge_template_id)){
                    if($recharge_template_id == 1){
                        $item->recharge_template_type = 1;
                        $item->recharge_template_id = 1;
                    }else{
                        $item->recharge_template_type = 2;
                        $item->recharge_template_id = $recharge_template_id;
                    }
                    $is_update = true;
                }
                if(isset($backhaul_setting_id)){
                    $item->backhaul_setting_id = $backhaul_setting_id;
                    $is_update = true;
                }
                if($is_update){
                    $item->save();
                }
            }
            return $this->response(SystemCode::SYSTEM_SUCCESS, '成功');
        }else{
            return $this->response(SystemCode::SYSTEM_ERROR,'数据不存在');
        }
    }

    public function deliverybackhaulSetting($company_id,$applet_id){
        $resultData[] = ['value' => 0,'label' => '不回传'];
        $returnData = DataBackhaulSetting::select(['id as value','name as label'])->where(['company_id' =>$company_id,'applet_id' => $applet_id])->get()->toArray();
        if(!empty($returnData)){

            $resultData = array_merge($resultData,$returnData);
            return $this->response(SystemCode::SYSTEM_SUCCESS, '获取成功',$resultData);
        }else{

            return $this->response(SystemCode::SYSTEM_ERROR,'数据不存在');
        }
    }
}